package com.zzyl.service.impl;

import cn.hutool.core.date.DateTime;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.date.LocalDateTimeUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.zzyl.base.PageResponse;
import com.zzyl.entity.Member;
import com.zzyl.entity.Reservation;
import com.zzyl.mapper.MemberMapper;
import com.zzyl.mapper.ReservationMapper;
import com.zzyl.service.ReservationService;
import com.zzyl.utils.UserThreadLocal;
import com.zzyl.vo.TimeCountVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.Date;
import java.util.List;

@Service
public class ReservationServiceImpl extends ServiceImpl<ReservationMapper, Reservation> implements ReservationService {

    @Autowired
    private ReservationMapper reservationMapper;
    @Autowired
    private MemberMapper memberMapper;
    //查询当天取消预约数量
    @Override
    public int getCancelCount() {
        Long updateBy = UserThreadLocal.getUserId();//获取当前用户id
        DateTime begin = DateUtil.beginOfDay(new Date());//当天开始
        DateTime end = DateUtil.endOfDay(new Date());//当天结束
        return getBaseMapper().getCancelCount(updateBy, begin, end);

    }

    //查询剩余预约次数
    @Override
    public List<TimeCountVo> getRemainingCount(Long time) {
        LocalDateTime begin = LocalDateTimeUtil.of(time);
        LocalDateTime end = begin.plusDays(1);
        return getBaseMapper().getRemainingCount(begin, end);
    }

    //新增预约
    @Override
    public void saveReservation(Reservation reservation) {
        int cancelCount = getCancelCount();
        if (cancelCount >= 3){
            throw new RuntimeException("预约失败，您今日预约次数已用完");
        }
        reservation.setStatus(0);//待报道

        try {

            reservationMapper.insert(reservation);
        }catch (Exception e){
            throw new RuntimeException("预约失败，此手机号已预约该时间");
        }

    }

    //分页查询
    @Override
    public PageResponse<Reservation> findByIdPage(Integer status, Integer pageNum, Integer pageSize) {
        //1.分页
        Page<Reservation> page = new Page<>(pageNum, pageSize);
        //2.设置业务
        LambdaQueryWrapper<Reservation> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(status != null,Reservation::getStatus, status)
                .eq(Reservation::getUpdateBy, UserThreadLocal.getUserId());
        Page<Reservation> reservationPage = reservationMapper.selectPage(page, wrapper);
        reservationPage.getRecords().forEach(reservation -> {
            Member member = memberMapper.selectById(reservation.getCreateBy());
            if (member != null){
                reservation.setCreator(member.getName());

            }
        });
        return new PageResponse<>(reservationPage);
    }


}
